﻿using nplJobsBLL.Common;
using nplJobsBLL.ProcessEmployeer;
using nplJobsCommon.Common;
using nplJobsCommon.Employeer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using nplJobsDAL.Insert;
using nplJobsDAL.Update;
using nplJobsDAL.Delete;

public partial class Employeer_EmployeerEntry : BasePage // System.Web.UI.Page
{
    private string NEPAL_ID = WebConfigurationManager.AppSettings["NEPAL_ID"];//140 == Nepal
    private string KATHMANDU_ID = WebConfigurationManager.AppSettings["KATHMANDU_ID"];//29 == Kathmandu

    public string CompanyImageFolder
    {
        get
        {
            return WebConfigurationManager.AppSettings["COMPANY_IMAGE_FOLDER"];
        }
    }

    public string EmployeerID
    {
        get
        {
            if (Session["userInfo"] != null)
                return ((MembershipUser)Session["userInfo"]).ProviderUserKey.ToString();
            else
                return string.Empty;
        }
    }

    #region Load Inital DropDownLists

    /// <summary>
    ///This function loads country information
    /// </summary>
    #region  LoadCountry()
    public void LoadCountry()
    {
        try
        {
            ProcessCountry countries = new ProcessCountry();
            countries.invoke();
            ddlCountry.DataSource = countries.Country;
            ddlCountry.DataTextField = "Name";
            ddlCountry.DataValueField = "ID";
            ddlCountry.DataBind();
            ddlCountry.SelectedValue = NEPAL_ID; 
            ddlCountry_SelectedIndexChanged(null, null);
            ddlCity.SelectedValue = KATHMANDU_ID; 
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion


    /// <summary>
    ///This function loads industry information
    /// </summary>
    #region  LoadIndustry()
    public void LoadIndustry()
    {
        try
        {
            ProcessIndustry industries = new ProcessIndustry();
            industries.invoke();
            ddlIndustry.DataSource = industries.Industry;
            ddlIndustry.DataTextField = "Name";
            ddlIndustry.DataValueField = "ID";
            ddlIndustry.DataBind();
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion

    /// <summary>
    ///This function loads employee range information
    /// </summary>
    #region  LoadEmployeeRange()
    public void LoadEmployeeRange()
    {
        try
        {
            ProcessEmployeeRange employeerange = new ProcessEmployeeRange();
            employeerange.invoke();
            ddlRangeOfEmployeer.DataSource = employeerange.EmployeeRange;
            ddlRangeOfEmployeer.DataTextField = "Range";
            ddlRangeOfEmployeer.DataValueField = "ID";
            ddlRangeOfEmployeer.DataBind();
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion

    /// <summary>
    ///This function loads city
    /// </summary>
    #region  LoadCity()
    public void LoadCity(int CountryID)
    {
        try
        {
            ProcessSelectCity city = new ProcessSelectCity();
            city.countryID = CountryID;
            city.invoke();

            ddlCity.DataSource = city.City;
            ddlCity.DataTextField = "Name";
            ddlCity.DataValueField = "ID";
            ddlCity.DataBind();
 
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion

    /// <summary>
    ///This function loads city
    /// </summary>
    #region  LoadEmployeerType()
    public void LoadEmployeerType()
    {
        try
        {
            ProcessEmployeerType employeertype = new ProcessEmployeerType();
            employeertype.invoke();

            List<EmployeerType> lstEmployeerType = employeertype.EmployeerType;

            MembershipUser currentUser = nplJobsWebSite.Common.CurrentMembershipUser;
            if (currentUser != null)
            {
                EmployeerType et = new EmployeerType();
                if (currentUser.UserName.Equals(WebConfigurationManager.AppSettings["NEWS_PAPER_USER"]))
                {
                    et = lstEmployeerType.Where(w => w.ID == 34).FirstOrDefault(); //Newspaper/Magazine
                }
                else if (currentUser.UserName.Equals(WebConfigurationManager.AppSettings["GUVERNMENT_USER"]))
                {
                    et = lstEmployeerType.Where(w => w.ID == 55).FirstOrDefault(); //Government Organizations
                }
                lstEmployeerType.Remove(et);
            }

            ddlCompanyType.DataSource = lstEmployeerType;
            ddlCompanyType.DataTextField = "Type";
            ddlCompanyType.DataValueField = "ID";
            ddlCompanyType.DataBind();
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion

    /// <summary>
    ///This function loads employeer contact person's designation
    /// </summary>
    #region  LoadContactPersonDesignation()
    public void LoadContactPersonDesignation()
    {
        try
        {
            ProcessSelectDesignation designation = new ProcessSelectDesignation();
            designation.invoke();
            ddlDesignation.DataSource = designation.Designation;
            ddlDesignation.DataTextField = "DesignationName";
            ddlDesignation.DataValueField = "ID";
            ddlDesignation.DataBind();

            ddlPopupDesignation.DataSource = designation.Designation;
            ddlPopupDesignation.DataTextField = "DesignationName";
            ddlPopupDesignation.DataValueField = "ID";
            ddlPopupDesignation.DataBind();
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion
    
    #endregion

    #region Page events
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.Session["user"] != null && HttpContext.Current.Session["user"].Equals(General.Users.JobSeeker.ToString()))
        {
            Response.Redirect("../JobSeeker/EditProfile.aspx");
            return;
        }

        base.ReloadUserInfoSession();

        if (!IsPostBack)
        {
            LoadAllDropDown();
            LoadInitalData();

            Page.Title = "Employeer entry";
        }
        //imgEmployeerImage.Attributes.Add("src", Session["imagePath"] != null ? Session["imagePath"].ToString() : "../Images/company-photo.png");
        SetCompanyImage();
    }

    protected void asynPictureUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        string fileExt = !String.IsNullOrEmpty(e.FileName) ? Path.GetExtension(e.FileName).ToLower() : String.Empty;

        if (asyncupload.HasFile && (fileExt == ".jpg" || fileExt == ".JPG" || fileExt == ".gif" || fileExt == ".GIF" || fileExt == ".png" || fileExt == ".PNG") && int.Parse(e.FileSize) < 200000)
        {
            if (Session["imagePath"] != null && !string.IsNullOrEmpty(Session["imagePath"].ToString()))
            {
                if (File.Exists(Server.MapPath(Session["imagePath"].ToString())))
                    File.Delete(Server.MapPath(Session["imagePath"].ToString()));
            }

            string newFileName = "Emp_" + nplJobsWebSite.Common.CurrentMembershipUser.ProviderUserKey + "_" + e.FileName;
            string savePath = Server.MapPath("/" + CompanyImageFolder + "/" + newFileName);
            asyncupload.SaveAs(savePath);
            Session["imagePath"] = ("/" + CompanyImageFolder + "/" + newFileName);
            SetCompanyImage();

            Employeer employeer = nplJobsWebSite.Common.GetEmployeer((Guid)nplJobsWebSite.Common.CurrentMembershipUser.ProviderUserKey);
            if (employeer != null)
            {
                employeer.EmployeerImagePath = Session["imagePath"] != null ? Session["imagePath"].ToString() : String.Empty;
                ProcessInserEmployeer employeerinsert = new ProcessInserEmployeer();
                employeerinsert.Employeer = employeer;
                employeerinsert.Update();
            }
        }
    }

    protected void imgNoPhoto_OnClick(object sender, EventArgs e)
    {
        imgEmployeerImage.Attributes.Add("src", "../Images/company-photo.png");
        Session["imagePath"] = null;
    }

    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(ddlCountry.SelectedValue))
        {
            ddlCity.Visible = false;
            txtCity.Visible = false;
            if (!ddlCountry.SelectedValue.Equals(NEPAL_ID)) //140 == Nepal
            {
                txtCity.Visible = true;
            }
            else
            {
                ddlCity.Visible = true;
                LoadCity(int.Parse(ddlCountry.SelectedValue));
            }
        }
    }

    protected void btnSaveEmployeerEntry_Click(object sender, EventArgs e)
    {
        SaveEmployeerEntry();
    }
    
    protected void btnSelectContactPerson_Click(object sender, EventArgs e)
    {
    }
    #endregion
 
    #region SaveEmployeerEntry
    /// <summary>
    /// Save employeer entry
    /// </summary>
    private void SaveEmployeerEntry()
    {
        ProcessInserEmployeer employeerinsert = new ProcessInserEmployeer();
        try
        {
            MembershipUser currentUser = nplJobsWebSite.Common.CurrentMembershipUser;
            if (currentUser != null)
            {
                Employeer employeer = nplJobsWebSite.Common.GetEmployeer((Guid)currentUser.ProviderUserKey);
                if (employeer == null)
                    employeer = new Employeer();

                employeer.EmployeerID = (Guid)currentUser.ProviderUserKey;
                employeer.CompanyName = !String.IsNullOrEmpty(txtCompanyName.Text) ? txtCompanyName.Text.Trim() : String.Empty;
                employeer.LocationID = 1;
                //employeer.CompanyImage = !String.IsNullOrEmpty(txtFirstName.Text) ? txtFirstName.Text.Trim() : String.Empty;
                employeer.EmployeerTypeID = !String.IsNullOrEmpty(ddlCompanyType.SelectedValue) ? int.Parse(ddlCompanyType.SelectedValue) : -1;
                employeer.EmployeeRangeID = !String.IsNullOrEmpty(ddlRangeOfEmployeer.SelectedValue) ? int.Parse(ddlRangeOfEmployeer.SelectedValue) : -1;
                employeer.CompanyDescription = !String.IsNullOrEmpty(txtCompanyDescription.Text) ? txtCompanyDescription.Text.Trim() : String.Empty;
                employeer.IndustryTypeID = !String.IsNullOrEmpty(ddlIndustry.SelectedValue) ? int.Parse(ddlIndustry.SelectedValue) : -1;
                //employeer.EmployeerImagePath = Session["imagePath"] != null ? Session["imagePath"].ToString() : String.Empty;

                employeer.Address = !String.IsNullOrEmpty(txtAddress.Text) ? txtAddress.Text.Trim() : String.Empty;
                employeer.Country = !String.IsNullOrEmpty(ddlCountry.SelectedValue) ? int.Parse(ddlCountry.SelectedValue) : -1;

                if (employeer.Country.ToString() != NEPAL_ID)
                {
                    employeer.CityName = txtCity.Text.Trim();
                    employeer.City = -1;
                }
                else
                {
                    employeer.CityName = string.Empty;
                    employeer.City = !String.IsNullOrEmpty(ddlCity.SelectedValue) ? int.Parse(ddlCity.SelectedValue) : -1;
                }

                employeer.Phone = !String.IsNullOrEmpty(txtPhone.Text) ? txtPhone.Text.Trim() : String.Empty;
                employeer.MobilePhone = !String.IsNullOrEmpty(txtMobilePhone.Text) ? txtMobilePhone.Text.Trim() : String.Empty;
                employeer.Fax = !String.IsNullOrEmpty(txtFax.Text) ? txtFax.Text.Trim() : String.Empty;
                employeer.HomePageUrl = !String.IsNullOrEmpty(txtWebsiteUrl.Text) ? txtWebsiteUrl.Text.Trim() : String.Empty;
                //employeer.Password = !String.IsNullOrEmpty(txtPassword.Text) ? txtPassword.Text.Trim() : String.Empty;
                if (!string.IsNullOrEmpty(hfContactPersonID.Value))
                    employeer.ContactPersonID = Convert.ToInt64(hfContactPersonID.Value);

                EmployeerContactPerson ecp = new EmployeerContactPerson();
                ecp.EmployeerID = employeer.EmployeerID;
                ecp.FirstName = !String.IsNullOrEmpty(txtFirstName.Text) ? txtFirstName.Text.Trim() : String.Empty;
                ecp.LastName = !String.IsNullOrEmpty(txtLastName.Text) ? txtLastName.Text.Trim() : String.Empty;
                ecp.DesignationID = !String.IsNullOrEmpty(ddlDesignation.SelectedValue) ? int.Parse(ddlDesignation.SelectedValue) : -1;
                ecp.Email = !String.IsNullOrEmpty(txtEmail.Text) ? txtEmail.Text.Trim() : String.Empty;
                ecp.TitleID = !String.IsNullOrEmpty(ddlTitle.SelectedValue) ? int.Parse(ddlTitle.SelectedValue) : -1;
                ecp.ContactNumber = !String.IsNullOrEmpty(txtContactNumber.Text) ? txtContactNumber.Text.Trim() : String.Empty;

                employeer.EmployeerContactPerson = ecp;
                employeerinsert.Employeer = employeer;
                employeerinsert.invoke();
                lblMsg.Text = "Saved Successfully";
                lblMsg.Visible = true;
            }
        }
        catch (Exception exp)
        {
            lblMsg.Text = exp.Message;
            lblMsg.Visible = true;
        }
    }
		 
	#endregion

    #region LoadCurrentPassword
    [WebMethod]
    public static string LoadCurrentPassword()
    {
        try
        {
            string empCurrPassword = String.Empty;

            empCurrPassword = "pass";
            return empCurrPassword;
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion

    private void SetCompanyImage()
    {
        imgEmployeerImage.ImageUrl = Session["imagePath"] != null ? Session["imagePath"].ToString() : "../Images/company-photo.png";
    }

    private void LoadInitalData()
    {
        MembershipUser currentUser = nplJobsWebSite.Common.CurrentMembershipUser;
        if (currentUser != null)
        {
            Employeer employeer = nplJobsWebSite.Common.GetEmployeer((Guid)currentUser.ProviderUserKey);
            if (employeer != null)
            {
                txtCompanyName.Text = employeer.CompanyName;
                ddlCompanyType.SelectedValue = employeer.EmployeerTypeID.ToString();
                ddlRangeOfEmployeer.SelectedValue = employeer.EmployeeRangeID.ToString();
                txtCompanyDescription.Text = employeer.CompanyDescription;
                ddlIndustry.SelectedValue = employeer.IndustryTypeID.ToString();
                if (!string.IsNullOrEmpty(employeer.CompanyImage))
                    Session["imagePath"] = employeer.CompanyImage;
                //imgEmployeerImage.Attributes.Add("src", Session["imagePath"] != null ? Session["imagePath"].ToString() : string.Empty);
                SetCompanyImage();
                
                txtAddress.Text = employeer.Address;
                ddlCountry.SelectedValue = employeer.Country.ToString();

                ddlCity.Visible = false;
                txtCity.Visible = false;
                if (!ddlCountry.SelectedValue.Equals(NEPAL_ID))
                {
                    txtCity.Visible = true;
                    txtCity.Text = employeer.CityName;
                }
                else
                {
                    ddlCity.Visible = true;
                    ddlCity.SelectedValue = employeer.City.ToString();
                }
                
                txtPhone.Text = employeer.Phone;
                txtMobilePhone.Text = employeer.MobilePhone;
                txtFax.Text = employeer.Fax;
                txtWebsiteUrl.Text = "";
                txtWebsiteUrl.Text = employeer.HomePageUrl;

                if (employeer.EmployeerContactPerson != null)
                {
                    hfContactPersonID.Value = employeer.EmployeerContactPerson.ContactPersonID.ToString();
                    ddlTitle.SelectedValue = employeer.EmployeerContactPerson.TitleID.ToString();
                    txtFirstName.Text = employeer.EmployeerContactPerson.FirstName;
                    txtLastName.Text = employeer.EmployeerContactPerson.LastName;
                    ddlDesignation.SelectedValue = employeer.EmployeerContactPerson.DesignationID.ToString();
                    txtEmail.Text = employeer.EmployeerContactPerson.Email;
                    txtContactNumber.Text = employeer.EmployeerContactPerson.ContactNumber;
                    txtAlternativeNumber.Text = employeer.EmployeerContactPerson.AlternativeNumber;
                }
            }
            else
            {
                Session["user"] = null;
                Session["employeer"] = null;
                Response.Redirect("../Default.aspx");
            }
        }
    }

    private void LoadAllDropDown()
    {
        LoadEmployeerType();
        LoadEmployeeRange();
        LoadCountry();
        //LoadCity(-1);
        LoadIndustry();
        LoadContactPersonDesignation();
    }

    #region Multi Contact Person
    private static object GetObject(object parms, string key)
    {
        Dictionary<string, object> parmsList = ((Dictionary<string, object>)(parms));
        object value;
        parmsList.TryGetValue(key, out value);
        return (value == null || string.IsNullOrEmpty(value.ToString())) ? DBNull.Value : value;
    }

    [WebMethod]
    public static long SaveContactPerson(object parms)
    {
        EmployeerContactPerson employeerContactPerson = new nplJobsCommon.Employeer.EmployeerContactPerson();
        employeerContactPerson.EmployeerID = Guid.Parse(((MembershipUser)HttpContext.Current.Session["userInfo"]).ProviderUserKey.ToString()); ;

        if (GetObject(parms, "hdnContactPersonID") != DBNull.Value)
            employeerContactPerson.ContactPersonID = Convert.ToInt32(GetObject(parms, "hdnContactPersonID"));

        employeerContactPerson.TitleID = Convert.ToInt32(GetObject(parms, "ddlPopupTitle"));
        employeerContactPerson.FirstName = GetObject(parms, "txtPopupFirstName").ToString();
        employeerContactPerson.LastName = GetObject(parms, "txtPopupLastName").ToString();
        employeerContactPerson.ContactNumber = GetObject(parms, "txtPopupContactNumber").ToString();
        employeerContactPerson.AlternativeNumber = GetObject(parms, "txtPopupAlternativeContactNumber").ToString();
        employeerContactPerson.DesignationID = Convert.ToInt64(GetObject(parms, "ddlPopupDesignation"));
        employeerContactPerson.Email = GetObject(parms, "txtPopupEmail").ToString();

        if (employeerContactPerson.ContactPersonID < 1)
        {
            InsertContactPerson insertContactPerson = new InsertContactPerson();
            insertContactPerson.EmployeerContactPerson = employeerContactPerson;
            insertContactPerson.invoke();
            return insertContactPerson.lastEmployeerContactPersonID;
        }
        else
        {
            UpdateContactPerson updateContactPerson = new UpdateContactPerson();
            updateContactPerson.EmployeerContactPerson = employeerContactPerson;
            updateContactPerson.invoke();
            return employeerContactPerson.ContactPersonID;
        }
    }

    [WebMethod]
    public static string GetContactPerson(string contactPersonID)
    {
        ProcesEmployeerContactPerson procesEmployeerContactPerson = new ProcesEmployeerContactPerson();
        procesEmployeerContactPerson.employeerID = Guid.Parse(((MembershipUser)HttpContext.Current.Session["userInfo"]).ProviderUserKey.ToString());
        procesEmployeerContactPerson.contactPersonID = long.Parse(contactPersonID);
        procesEmployeerContactPerson.invoke();

        return new JavaScriptSerializer().Serialize(procesEmployeerContactPerson.employeerContactPerson.FirstOrDefault());
    }

    [WebMethod]
    public static int DeleteContactPerson(string contactPersonID)
    {
        ProcesEmployeerContactPerson procesEmployeerContactPerson = new ProcesEmployeerContactPerson();
        procesEmployeerContactPerson.employeerID = Guid.Parse(((MembershipUser)HttpContext.Current.Session["userInfo"]).ProviderUserKey.ToString());
        procesEmployeerContactPerson.contactPersonID = long.Parse(contactPersonID);
        procesEmployeerContactPerson.invoke();

        DeleteContactPerson deleteContactPerson = new DeleteContactPerson();
        deleteContactPerson.EmployeerContactPerson = procesEmployeerContactPerson.employeerContactPerson.FirstOrDefault();
        deleteContactPerson.invoke();

        return deleteContactPerson.isDeleted;
    }

    //[WebMethod]
    //public static bool RedirectJobSeeker()
    //{
    //    if (HttpContext.Current.Session["user"] != null && HttpContext.Current.Session["user"].Equals(General.Users.JobSeeker.ToString()))
    //    {
    //        return true;
    //    }
    //    return false;
    //}

    [WebMethod]
    public static string GetContactsPerson()
    {
        if (HttpContext.Current.Session["user"] != null && HttpContext.Current.Session["user"].Equals(General.Users.JobSeeker.ToString()))
        {
            HttpContext.Current.Response.Redirect("../JobSeeker/EditProfile.aspx");
        }

        ProcesEmployeerContactPerson procesEmployeerContactPerson = new ProcesEmployeerContactPerson();
        procesEmployeerContactPerson.employeerID = Guid.Parse(((MembershipUser)HttpContext.Current.Session["userInfo"]).ProviderUserKey.ToString());
        procesEmployeerContactPerson.invoke();        
        
        return new JavaScriptSerializer().Serialize(procesEmployeerContactPerson.employeerContactPerson);
    }

    #endregion
}